package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart> implements ShoppingCartService {

    /**
     * 减少购物车中套餐或者菜品的数量
     * 需求分析：
     * 如果数量减为0时，直接删除该条数据
     * @param shoppingCart
     */
    @Override
    public ShoppingCart sub(ShoppingCart shoppingCart) {
        //1。从购物车中获得菜品id或者套餐id
        Long dishId = shoppingCart.getDishId();
        Long setmealId = shoppingCart.getSetmealId();

        //2。判断是菜品还是套餐，并根据菜品或套餐id和用户id查询购物车中该数据的信息
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        if (dishId != null){ //如果是菜品
            queryWrapper.eq(ShoppingCart::getDishId, dishId);
        }else if (setmealId != null){ //如果是套餐
            queryWrapper.eq(ShoppingCart::getSetmealId, setmealId);
        }
        //确定是那个用户的购物车
        queryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        ShoppingCart cart = this.getOne(queryWrapper);

        //3。如果剩余数量大于1直接减1，如果为1直接删掉该条数据，否则抛出异常
        int number = cart.getNumber();
        if (number > 1){
            cart.setNumber(cart.getNumber() - 1);
            this.updateById(cart);
        }else if (number == 1){
            this.removeById(cart.getId());
        }else {
            throw new CustomException("菜品或者套餐数据异常！");
        }
        return cart;
    }

}
